<?php

/**
 * Created by PhpStorm.
 * User: LP
 * Date: 2017/12/10
 * Time: 11:33
 */
class FormAction
{
    /**
     * 添加表单或修改表单
     * @param string $formId 表单id(修改时传)
     * @param $formName             表单名称
     * @param $status               表单状态(是否开启 0-开启/1-关闭)
     * @param $type                 类型(1-付费表单/2-免费表单)
     * @param $vendorId             供应商id
     * @param $payPrice             付费价格
     * @param $supplyPrice          供货价格
     * @param $platCut              平台分成
     * @param $saleCut              销售分成
     * @param string $buttonWord 提交按钮文字
     * @param string $buttonColor 提交按钮颜色
     * @param string $field 表单属性json串
     * @param string $groupId 分组id用逗号拼接
     * @param int $pointSchemeId 积分方案id 0:取消关联
     * @return mixed
     */
    public function formAdd($formId = '', $formName, $status, $type, $vendorId = '', $payPrice = '', $supplyPrice = '',
                            $platCut = '', $saleCut = '', $buttonWord = '', $buttonColor = '', $field, $tagId = '', $pointSchemeId=-1)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        $fullName = Session::$user["fullName"];
        Session::switchCustomer(0);
        $formModel = M('form');
        $formFieldModel = M('form_field');
        $formTagListModel = M('form_tag_list');
        Session::switchCustomer($cid);

        /**3.组合数据*/
        $data['cid'] = $cid;
        $data['formName'] = $formName;
        $data['status'] = $status;
        $data['type'] = $type;
        $data['vendorId'] = $vendorId;
        $data['payPrice'] = $payPrice;
        $data['supplyPrice'] = $supplyPrice;
        $data['platCut'] = $platCut;
        $data['saleCut'] = $saleCut;
        $data['buttonWord'] = $buttonWord;
        $data['buttonColor'] = $buttonColor;
        $data['updateTime'] = date('Y-m-d H:i:s');
        $data['deleted'] = 0;

        //表单关联
        if($formId && ($pointSchemeId >= 0)){
            $relationRet = $formModel->where(['id' => $formId])->save(['pointSchemeId' => $pointSchemeId]);
            if(!is_numeric($relationRet)){
                Log::write('表单关联积分失败:'.$formModel->getDbError());
                Output::instance()->object([
                    'code' => -1,
                    'msg' => '保存失败',
                    'results' => []
                ]);
                return;
            }
            Output::instance()->object([
                'code' => 0,
                'msg' => '保存成功',
                'results' => []
            ]);
            return;
        }

        /**4.判断添加或修改,若是修改并删除分组及详情*/
        if (!empty($formId)) {
            $oldFormName = $formModel->where(['id' => $formId])->getField('formName');
            $result = $formModel->where(['id' => $formId])->save($data);
            $formFieldModel->where(['cid' => $cid, 'formId' => $formId])->delete();
            $formTagListModel->where(['formId' => $formId])->delete();

            R('Log/add', array('formManage', formManage, '表单管理', op_update, $formModel->getLastSql(), $fullName . '将表单名称' . $oldFormName . '改为' . $formName));
        } else {
            $data['createTime'] = date('Y-m-d H:i:s');
            $formId = $formModel->add($data);

            R('Log/add', array('formManage', formManage, '表单管理', op_add, $formModel->getLastSql(), $fullName . '添加表单' . $formName));
        }

        /**5.添加类型详情*/
        $fieldArr = json_decode($field, true);
        foreach ($fieldArr as $k => $v) {
            $v['cid'] = $cid;
            $v['formId'] = $formId;
            $v['createTime'] = date('Y-m-d H:i;s');
            $v['updateTime'] = date('Y-m-d H:i;s');
            $v['index'] = $k + 1;
            $formFieldModel->add($v);
        };

        /**6.添加分组*/
        if (!empty($tagId)) {
            $tagIds = explode(',', $tagId);
            foreach ($tagIds as $k => $v) {
                $groupInfo[$k]['tagId'] = $v;
                $groupInfo[$k]['formId'] = $formId;
                $groupInfo[$k]['cid'] = $cid;
            }
            $groupRes = $formTagListModel->addAll($groupInfo);
        }

        /**7.判断并返回*/
        if (is_numeric($result) || $formId) {
            $Out = [
                'code' => 0,
                'msg' => '保存成功',
                'data' => []
            ];
            Output::instance()->object($Out);
        } else {
            $Out = [
                'code' => 1,
                'msg' => '保存失败',
                'data' => []
            ];
            Output::instance()->object($Out);
        }


    }

    /**
     * 删除表单
     * @param $formId 表单id
     */
    public function formDelete($formId)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        $fullName = Session::$user["fullName"];
        Session::switchCustomer(0);
        $formModel = M('form');
        Session::switchCustomer($cid);

        /**3.删除*/
        $oldFormName = $formModel->where(['id' => $formId])->getField('formName');
        $result = $formModel->where(['id' => $formId])->setField('deleted', 1);

        /**4.判断是否删除成功并返回*/
        if ($result) {
            R('Log/add', array('formManage', formManage, '表单管理', op_delete, $formModel->getLastSql(), $fullName . '删除表单' . $oldFormName));
            $Out = [
                'code' => 0,
                'msg' => '删除成功',
                'data' => []
            ];
            Output::instance()->object($Out);
        } else {
            $Out = [
                'code' => 1,
                'msg' => '删除失败',
                'data' => []
            ];
            Output::instance()->object($Out);
        }
    }

    /**
     * 表单详情
     * @param $formId 表单id
     */
    public function formDetail($formId)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $formModel = M('form');
        $formFieldModel = M('form_field');
        $formTagListModel = M('form_tag_list');
        $miVendorModel = M('mivendor');
        Session::switchCustomer($cid);

        /**3.查询表单详情*/
        $formInfo = $formModel->where(['id' => $formId])->find();
        $formInfo['field'] = $formFieldModel->where(['formId' => $formId])->select();
        $formInfo['vendorName'] = $miVendorModel->where(['id' => $formInfo['vendorId']])->getField('name');
        $groupInfo = $formTagListModel->alias('a')->where(['formId' => $formId])->join('wx_form_tag as b On a.tagId=b.id')->field('group_concat(a.tagId) as tagId,group_concat(b.name) as tagName')->find();
        $formInfo['tagName'] = $groupInfo['tagName'];
        $formInfo['tagId'] = $groupInfo['tagId'];

        /**4.返回*/
        if (!empty($formInfo)) {
            $Out = [
                'code' => 0,
                'msg' => '获取表单详情成功',
                'data' => $formInfo
            ];
            Output::instance()->object($Out);
        } else {
            $Out = [
                'code' => 0,
                'msg' => '获取表单详情失败',
                'data' => []
            ];
            Output::instance()->object($Out);
        }
    }

    /**
     * 系统类型展示列表
     */
    public function fieldSysList()
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $formFieldSysModel = M('form_field_sys');
        Session::switchCustomer($cid);

        /**3.查询数据*/
        $arr = $formFieldSysModel->select();
        foreach ($arr as $k => $v) {
            $arr[$k]['default'] = '';
            $arr[$k]['requird'] = '';
            $arr[$k]['options'] = '';
        }

        /**4.返回数据*/
        $Out = [
            'code' => 0,
            'msg' => '系统类型返回',
            'data' => $arr
        ];
        Output::instance()->object($Out);
    }

    /**
     * 表单列表
     * @param string $keyword 关键字搜索
     * @param string $type 类型(1-付费表单/2-免费表单)
     * @param string $status 表单状态(是否开启 0-开启/1-关闭)
     * @param int $start 开始条数
     * @param int $limit 每页条数
     */
    public function formList($keyword = '', $type = '', $status = 2, $start = 0, $limit = 10)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $formModel = M('form');
        $formTagListModel = M('form_tag_list');
        Session::switchCustomer($cid);
        /**3.查询数据*/
        !empty($keyword) ? $where['a.formName'] = array('like', "%$keyword%") : '';
        !empty($type) ? $where['a.type'] = array('eq', $type) : '';
        if($status != 2){
            $where['a.status'] = array('eq', $status);
        }
        $where['a.deleted'] = array('eq', 0);
        $where['a.cid'] = array('eq', $cid);
        $formInfo = $formModel->alias('a')
            ->join('wx_module_point_scheme s on s.id=a.pointSchemeId')
            ->where($where)
            ->order('a.updateTime desc')
            ->limit($start, $limit)
            ->field('a.id,a.formName,a.status,a.createTime,a.updateTime,a.type,a.pointSchemeId,s.name as pointSchemeName')
            ->select();
        $count = $formModel->alias('a')->where($where)->count();

        /**4.查询分组*/
        foreach ($formInfo as $k => $v) {
            $groupInfo = $formTagListModel->alias('a')->where(['formId' => $v['id']])->join('wx_form_tag as b On a.groupId=b.id')->field('group_concat(a.tagId) as tagId,group_concat(b.tagName) as tagName')->find();
            $formInfo[$k]['tagName'] = $groupInfo['tagName'];
            $formInfo[$k]['tagId'] = $groupInfo['tagId'];
        }
        empty($formInfo) ? $formInfo = [] : '';
        /**5.返回*/
        $Out = [
            'code' => 0,
            'msg' => '获取表单成功',
            'data' => $formInfo,
            'count' => $count,
        ];
        Output::instance()->object($Out);
    }


    /**
     * 表单一级分类添加
     * @param $groupName     /一级分类名称
     */
    public function formTagGroupAdd($id = '', $groupName)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $formTagGroupInfoModel = M('form_tag_group');
        Session::switchCustomer($cid);

        /**4.不存在则添加*/
        $data['groupName'] = $groupName;
        $data['updateTime'] = date('Y-m-d H:i:s');
        if ($id) {
            $result = $formTagGroupInfoModel->where(['id' => $id])->save($data);
        } else {
            $data['cid'] = $cid;
            $data['deleted'] = 0;
            $data['createTime'] = date('Y-m-d H:i:s');
            $result = $formTagGroupInfoModel->add($data);
        }
        $sql = $formTagGroupInfoModel->getLastSql();


        /**5.判断是否添加成功*/
        if (is_numeric($result)) {
            if (!$id) {
                R('Log/add',array('formLabel', '', '表单标签', op_add, $sql, '添加表单标签分组：' . $groupName));
            } else {
                R('Log/add',array('formLabel', '', '表单标签', op_update, $sql, '更新表单标签分组：' . $groupName));
            }
            $Out = [
                'code' => 0,
                'msg' => '添加成功',
                'data' => []
            ];
            Output::instance()->object($Out);
            return;
        } else {
            $Out = [
                'code' => 1,
                'msg' => '添加失败',
                'data' => []
            ];
            Output::instance()->object($Out);
            return;
        }


    }

    /**
     * 表单一级分类删除
     * @param $groupId     分组Id
     */
    public function formGroupDelete($id)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $formTagGroupInfoModel = M('form_tag_group');
        $formTagModel = M('form_tag');
        Session::switchCustomer($cid);

        /**3.删除*/
        $where['id'] = array('eq', $id);
        $where['cid'] = array('eq', $cid);
        $result = $formTagGroupInfoModel->where($where)->setField('deleted', 1);
        $sql = $formTagGroupInfoModel->getLastSql();
        $groupName = $formTagGroupInfoModel->where($where)->getField('groupName');

//        $formTagModel->where(['groupId' => $groupId])->setField('deleted', 1);

        /**4.判是否删除成功断*/
        if (is_numeric($result)) {
            R('Log/add',array('formLabel', '', '表单标签', op_delete, $sql, '删除表单标签分组' . $groupName));
            $Out = [
                'code' => 0,
                'msg' => '删除成功',
            ];
            Output::instance()->object($Out);
        } else {
            $Out = [
                'code' => 1,
                'msg' => '删除失败',
            ];
            Output::instance()->object($Out);
        }
    }

    /**
     * 获取表单一级分类详情
     * @param $id 表单一级分类id
     */
    public function formGroupDetail($id)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $formTagGroupInfoModel = M('form_tag_group');
        $formTagModel = M('form_tag');
        Session::switchCustomer($cid);

        /**3.查询数据 */
        $where['id'] = array('eq', $id);
        $arr = $formTagGroupInfoModel->where($where)->find();

        /**4.返回数据*/
        if (!empty($arr)) {
            $Out = [
                'code' => 0,
                'msg' => '获取分组标签成功',
                'data' => $arr,
            ];
            Output::instance()->object($Out);
        } else {
            $Out = [
                'code' => 1,
                'msg' => '获取分组标签失败',
                'data' => [],
            ];
            Output::instance()->object($Out);
        }
    }

    /**
     * 表单一级分类列表
     */
    public function formGroupList($keyword = '', $start = 0, $limit = 10)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $formTagGroupInfoModel = M('form_tag_group');
        Session::switchCustomer($cid);

        /**3.删除*/
        $where['cid'] = array('eq', $cid);
        $where['deleted'] = array('eq', 0);
        empty($keyword) ? '' : $where['tagName'] = array('like', "%$keyword%");
        $GroupInfo = $formTagGroupInfoModel->where($where)->order('id desc')->limit($start, $limit)->select();

        if(!empty($GroupInfo)){
            $Out = [
                'code' => 0,
                'msg' => '获取标签分组标签成功',
                'data' => $GroupInfo,
            ];
            Output::instance()->object($Out);
        }else{
             $Out = [
                'code' => 1,
                'msg' => '获取标签分组标签为空',
                'data' => [],
            ];
            Output::instance()->object($Out);
        }
    }


    /**
     * 获取表单一二级分类
     */
    public function getFormTag()
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $formTagGroupInfoModel = M('form_tag_group');
        $formTagModel = M('form_tag');
        Session::switchCustomer($cid);

        /**3.查询数据*/
        $where['cid'] = array('eq', $cid);
        $where['deleted'] = array('eq', 0);
        $arr = $formTagGroupInfoModel->where($where)->select();
        foreach ($arr as $k => $v) {
            $tag = $formTagModel->where(['groupId' => $v['id'], 'deleted' => 0])->select();
            $arr[$k]['tag'] = $tag;
        }

        /**4.返回数据*/
        if (!empty($arr)) {
            $Out = [
                'code' => 0,
                'msg' => '获取分组标签成功',
                'data' => $arr,
            ];
            Output::instance()->object($Out);
        } else {
            $Out = [
                'code' => 1,
                'msg' => '获取分组标签失败',
                'data' => [],
            ];
            Output::instance()->object($Out);
        }

    }


    /**
     * 二级标签列表
     */
    public function tagList($keyword = '')
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $formTagModel = M('form_tag');
        Session::switchCustomer($cid);

        /**3.查询数据*/
        $where['groups.cid'] = array('eq', $cid);
        $where['tag.deleted'] = array('eq', 0);
        empty($keyword) ? '' : $where['tag.tagName'] = array('like', '%' . $keyword . '%');
        $arr = $formTagModel->alias('tag')->where($where)->join("wx_form_tag_group as groups On tag.groupId=groups.id")->field('tag.*,groups.groupName')->select();

        /**4.返回数据*/
        if (!empty($arr)) {
            $Out = [
                'code' => 0,
                'msg' => '获取分组标签列表成功',
                'data' => $arr,
            ];
            Output::instance()->object($Out);
        } else {
            $Out = [
                'code' => 1,
                'msg' => '获取分组标签列表失败',
                'data' => [],
            ];
            Output::instance()->object($Out);
        }
    }

    /**
     * 删除表单二级标签
     * @param $id      标签id
     */
    public function deleteFormTag($id)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        /**2.实例化数据库表*/
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $formTagModel = M('form_tag');
        Session::switchCustomer($cid);

        /**3.删除标签*/
        $result = $formTagModel->where("id=$id")->setField('deleted', 1);
        $groupName = $formTagModel->where("id=$id")->getField('name');

        /**4.判断是否删除成功*/
        if ($result) {
            R('Log/add',array('formLabel', '', '表单标签', op_delete, $formTagModel->getLastSql(), '删除表单标签：' . $groupName));
            Output::instance()->resultCode(code_success);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    /**
     * 二级标签详情
     * @param $id      标签id
     */
    public function formTagDetail($id)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        /**2.实例化数据库表*/
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $formTagModel = M('form_tag');
        Session::switchCustomer($cid);

        /**3.查询数据*/
        $tagInfo = $formTagModel->alias('Tag')->where(['Tag.id' => $id])->join("wx_form_tag_group as groups On Tag.groupId=groups.id")->field('Tag.*,groups.groupName')->find();
        /**4.返回标签信息返回*/
        $Out = [
            'code' => 1,
            'msg' => '获取标签信息',
            'data' => $tagInfo,
        ];
        Output::instance()->object($Out);
    }

    /**
     * 表单二级分类添加
     * @param $id            /二级分类id
     * @param $tagName       /二级分类名称
     * @param $description   /二级分类描述
     * @param $number        /二级分类编号
     * @param $picUrl        /二级分类封面
     * @param $title         /二级分类标题
     * @param $groupId       /二级分类对应一级分类Id
     */
    public function formTagAdd($id = '', $tagName, $description = '', $number = '', $picUrl = '', $title = '', $groupId = '')
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $formTagModel = M('form_tag');
        $formTagGroupModel = M('form_tag_group');
        Session::switchCustomer($cid);

        /**4.不存在则添加*/
        $data['name'] = $tagName;
        $data['description'] = $description;
        $data['number'] = $number;
        $data['picUrl'] = $picUrl;
        $data['title'] = $title;
        if (!$groupId) {
            $groupId = $formTagGroupModel->where("groupName='默认' and cId=$cid")->field("id")->find();
            $groupId = $groupId['id'];
        }
        if (!$groupId) {
            $data['groupName'] = '默认';
            $data['deleted'] = 0;
            $data['cid'] = $cid;
            $data['createTime'] = date("Y-m-d H:i:s");
            $groupId = $formTagGroupModel->add($data);
        }
        $data['groupId'] = $groupId;

        $data['updateTime'] = date('Y-m-d H:i:s');
        if ($id) {
            $result = $formTagModel->where(['id' => $id])->save($data);
        } else {
            $data['cid'] = $cid;
            $data['deleted'] = 0;
            $data['createTime'] = date('Y-m-d H:i:s');
            $result = $formTagModel->add($data);
        }
        $sql = $formTagModel->getLastSql();


        /**5.判断是否添加成功*/
        if (is_numeric($result)) {
            if (!$id) {
                R('Log/add',array('formLabel', '', '表单标签', op_add, $sql, '添加表单标签：' . $tagName));
            } else {
                R('Log/add',array('formLabel', '', '表单标签', op_update, $sql, '更新表单标签：' . $tagName));
            }
            $Out = [
                'code' => 0,
                'msg' => '添加成功',
                'data' => []
            ];
            Output::instance()->object($Out);
            return;
        } else {
            $Out = [
                'code' => 1,
                'msg' => '添加失败',
                'data' => []
            ];
            Output::instance()->object($Out);
            return;
        }


    }


}